<?php

namespace app\common\model;

use app\admin\library\Auth;
use think\Model;

class Brand extends Model
{
    // 表名
    protected $name = 'brand';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;
    
    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text',
        'update_time_text'
    ];
    

    
    public function getStatusList()
    {
        return ['1' => '启用', '0' => '禁用'];
    }     


    public function getStatusTextAttr($value, $data)
    {        
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['create_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['update_time'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    public function category(){
    	return $this->belongsTo('goodsCategory', 'category_id', 'id','', 'left')->setEagerlyType(0);
    }
    
    public function checkBrand($name){
    	$row = $this->where(['name' => $name])->find();
    	if($row){
    		return $row['id'];
	    }
	    
	    $id = $this->insertGetId([
	        'name' => $name,
	    ]);
    	
    	return $id;
    }
}
